<template>
  <div>
    <div class="wrapper">
      <div class="container">
        <div v-show="isShowFileUploadDialog"
             class="dialog-upload fixed-dialog">
          <div class="log">
            <li v-for="item in currentUploadFile"
                :key="item.id">
              <span>{{ item.name }}</span>
              <span class="progress"
                    :style="'width:' + item.progress">{{ item.progress }}</span>
            </li>
          </div>
        </div>
        <div v-show="isShowEditDialog"
             class="dialog-edit fixed-dialog">
          <div class="edit">
            <header>{{ editDialogTitle }}</header>
            <textarea v-model="editContent"></textarea>
            <footer>
              <button @click="onEditDialogAction(1)">保存</button>
              <button @click="onEditDialogAction(0)">取消</button>
            </footer>
          </div>
        </div>
        <header-components :status="1"></header-components>
        <div class="file-manager">
          <aside>
            <nav>
              <ul>
                <li :class="status == '0' ? 'select' : ''">
                  <a href="/">我的电脑</a>
                </li>
                <li :class="status == '1' ? 'select' : ''">
                  <a href="mark">收藏的文件夹</a>
                </li>
              </ul>
            </nav>
          </aside>

          <div mouse
               class="file-window">
            <menu v-show="isShowMenu"
                  :style="
								'left:' + menuX + 'px;' + 'top:' + menuY + 'px'
							"
                  class="file-menu">
              <li @click="markFile(status == '1' ? false : true)">
                {{ status == '1' ? '取消收藏' : '收藏' }}
              </li>
              <li @click="deleteFile()">删除</li>
              <li @click="editFile()">编辑</li>
              <li @click="downFile()">下载</li>
            </menu>
            <div v-show="showFileMask"
                 class="file-draw-panel">
              释放鼠标进行上传
            </div>
            <div class="file-window-header">
              <button @click="listDir('/')">
                {{ status == '1' ? '我的收藏' : '/' }}
              </button>
              <button @click="onNavClick(index)"
                      v-for="(item, index) in currentAbsPath"
                      :key="index">
                {{ item }}
              </button>
            </div>
            <div class="file-window-body">
              <ul>
                <li @mousemove="onItemMouseMove"
                    @click="hideRightMenu(i)"
                    @dblclick="onFileClick(i)"
                    v-for="(item, i) in files"
                    :key="i"
                    :data-index="i"
                    :id="'file-' + i">
                  <div class="file {type}">
                    <div class="graphical">
                      <img :data-index="i"
                           @contextmenu="onRightClick"
                           :src="
													HOST +
														'/api/res/convertIcon/?path=' +
														item.absPath
												" />
                    </div>
                    <span>{{ item.name }}</span>
                  </div>
                </li>
              </ul>
            </div>
            <div class="file-window-footer"></div>
          </div>
        </div>

        <div class="file-transfer-list"></div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '../apis/index'
import headerComponents from '../components/headerNav.vue'
export default {
  props: ['status'],
  data() {
    return {
      showFileMask: false,
      files: [],
      currentAbsPath: [],
      elemetnNode: '',
      menuX: 10,
      menuY: 10,
      isShowMenu: false,
      isShowFileUploadDialog: false,
      currentSelectIndex: {},
      HOST: '',
      currentUploadFile: [],
      isShowEditDialog: false,
      editContent: '',
      editDialogTitle: ''
    }
  },
  components: {
    headerComponents
  },
  mounted: function() {
    var _this = this
    this.HOST = this.global.BASE_URL
    document
      .querySelector('.file-window')
      .addEventListener('dragenter', function(e) {
        _this.elemetnNode = e.target
        _this.showFileMask = true
      })
    document
      .querySelector('.file-window')
      .addEventListener('dragleave', function(e) {
        if (_this.elemetnNode == e.target) {
          _this.showFileMask = false
        }
      })
    document
      .querySelector('.file-window')
      .addEventListener('dragover', function(e) {
        e.preventDefault()
      })
    document
      .querySelector('.file-window')
      .addEventListener('drop', function(e) {
        e.preventDefault()
        var dt = e.dataTransfer
        _this.showFileMask = false
        _this.uploadFile(dt.files)
      })

    var list = this.status == '1' ? api.listMark() : api.listDir('/')
    list
      .then(res => {
        this.files = res.data
      })
      .catch(res => {})
  },

  methods: {
    guid() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
      }
      return (
        S4() +
        S4() +
        '-' +
        S4() +
        '-' +
        S4() +
        '-' +
        S4() +
        '-' +
        S4() +
        S4() +
        S4()
      )
    },
    onItemMouseMove() {
      this.hideRightMenu()
    },
    getCurrentSelectFile() {
      return this.files[this.currentSelectIndex]
    },
    /**
     * 从currentAbsPath构建完整路径
     */
    buildCurrentPath() {
      let path = '/'
      for (let v of this.currentAbsPath.values()) {
        path += v + '/'
      }
      path = path.substr(0, path.length - 1)
      return path
    },
    /**
     * 上传文件
     */
    uploadFile(files) {
      this.isShowFileUploadDialog = true
      for (let i = 0; i !== files.length; i++) {
        /**
         * 构建FormData对象
         */
        let formData = new FormData()
        formData.append('upfile', files[i], files[i].name)
        formData.append('path', this.buildCurrentPath())

        let uuid = this.guid()

        this.currentUploadFile.push({
          id: uuid,
          name: files[i].name,
          progress: 0
        })

        api
          .uploadFile(formData, res => {
            let uploadItemIndex = this.currentUploadFile.findIndex(function(
              item
            ) {
              return item.id === uuid
            })

            this.currentUploadFile[uploadItemIndex].progress = res.progress

            if (res.progress == '100%') {
              this.listDir(this.buildCurrentPath())
              setTimeout(() => {
                let uploadItemIndex = this.currentUploadFile.findIndex(function(
                  item
                ) {
                  return item.id === uuid
                })

                this.currentUploadFile.splice(uploadItemIndex, 1)

                if (this.currentUploadFile.length == 0) {
                  setTimeout(() => {
                    this.isShowFileUploadDialog = false
                  }, 500)
                }
              }, 1500)
            }
          })
          .then(res => {
            if (res.data.code < 0) {
              this.$toast('提示', res.data.msg, i => {})
            }
          })
      }
    },
    /**
     * 收藏文件
     */
    markFile(flag) {
      this.hideRightMenu()
      let current = this.getCurrentSelectFile()
      api
        .markFile(current.absPath, flag)
        .then(res => {
          this.$toast('提示', res.msg, i => {
            if (!flag) {
              this.files.splice(this.currentSelectIndex, 1)
            }
          })
        })
        .catch(res => {})
    },

    /**
     * 下载文件
     */
    downFile() {
      this.hideRightMenu()
      if (this.files[this.currentSelectIndex].file) {
        window.open(
          api.downloadFile(this.files[this.currentSelectIndex].absPath)
        )
      } else {
        this.$toast(
          '提示',
          '此文件为文件夹，服务器将在打包ZIP后进行下载，这可能需要写时间',
          i => {
            if (i == 0) {
              window.open(
                api.downloadFile(this.files[this.currentSelectIndex].absPath)
              )
            }
          }
        )
      }
    },
    /**
     * 编辑文件
     */
    editFile(file) {
      this.hideRightMenu()
      file = file || this.getCurrentSelectFile().absPath
      this.editDialogTitle = file
      api
        .getFileContent(file)
        .then(res => {
          this.isShowEditDialog = true
          this.editContent = res.data
        })
        .catch(res => {})
    },
    /**
     * 删除文件
     */
    deleteFile() {
      this.hideRightMenu()
      this.$toast('提示', '在问你一遍，确认删除吗?', i => {
        if (i == 0) {
          api.deleteFile(this.getCurrentSelectFile().absPath).then(res => {
            if (res.code == 0) {
              this.files.splice(this.currentSelectIndex, 1)
            } else {
              this.$toast('提示', res.msg, i => {})
            }
          })
        }
      })
    },
    /**
     * 列举文件
     */
    listDir(dir) {
      if (dir != '/') {
        this.currentAbsPath = dir.split('/')
        this.currentAbsPath.splice(0, 1)
      } else {
        this.currentAbsPath = []
      }
      var list = api.listDir(dir)
      if (this.status == '1' && dir == '/') {
        list = api.listMark()
      }
      list
        .then(res => {
          this.files = res.data
        })
        .catch(res => {})
    },
    onNavClick(index) {
      this.hideRightMenu()
      var path = '/'
      for (let i = 0; i < index + 1; i++) {
        const element = this.currentAbsPath[i]
        path += element + '/'
      }
      this.listDir(path.substr(0, path.length - 1))
    },
    onFileClick(index) {
      if (!this.hideRightMenu()) {
        if (this.files[index].file) {
          this.editFile(this.files[index].absPath)
          this.currentSelectIndex = index
        } else {
          this.listDir(this.files[index].absPath)
        }
      }
    },
    /**
     * 文件右击
     */
    onRightClick(e) {
      this.currentSelectIndex = e.target.getAttribute('data-index')
      this.isShowMenu = true
      this.menuX = e.x - 5
      this.menuY = e.y
      return false
    },
    hideRightMenu() {
      if (this.isShowMenu) {
        this.isShowMenu = false
        return true
      }
      this.isShowMenu = false
      return this.isShowMenu
    },
    onEditDialogAction(whi) {
      if (whi == 0) {
        this.isShowEditDialog = false
        return
      }

      api
        .setFileContent(this.getCurrentSelectFile().absPath, this.editContent)
        .then(res => {
          this.isShowEditDialog = false
          this.$toast('提示', res.msg, i => {})
        })
        .catch(res => {})
    }
  }
}
</script>

<style lang="less">
@import url('../style/less/index.less');
@import url('../style/less/base.less');
@import url('../style/less/dialog.less');
@import url('../style/less/file-style.less');
</style>
